package com.youlu.campus.service.config.impl;

import com.youlu.campus.entity.OuterAppConfig;
import com.youlu.campus.service.config.OuterAppConfigService;
import com.youlu.campus.service.config.OuterAppIpConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class OuterAppConfigServiceImpl implements OuterAppConfigService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Lazy
    @Autowired
    private OuterAppIpConfigService outerAppIpConfigService;

    @Override
    public OuterAppConfig findByType(String type) {
        Query q = new Query();
        q.addCriteria(Criteria.where("type").is(type));
        return mongoTemplate.findOne(q, OuterAppConfig.class);
    }

    @Override
    public boolean check(String ip, String domain, String type) {
        log.info(":>>> 开始校验外部应用:{},{},{}", ip, domain, type);
        OuterAppConfig config = this.findByType(type);
        if (Objects.isNull(config)) {
            log.error(":>>> 外部应用:{},不存在",type);
            return true;
        }
        return outerAppIpConfigService.exist(config.getId(),ip, domain);
    }

    @Override
    public OuterAppConfig findById(String id) {
        Query q = new Query();
        q.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(q, OuterAppConfig.class);
    }
}
